package net.andersand.games.yatzy;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.*;

/**
 * Implemented using Java Sound API
 * @author asn
 *
 */
class DefaultSound implements Sound {

	URL url;
	Clip clip;
	private static final int STOP_FRAME = 20000;
	
	DefaultSound(URL resource) {
		this.url = resource;
		load();
	}
	
	void load() {
		try {
			AudioInputStream ais = AudioSystem.getAudioInputStream(url);
			AudioFormat format = ais.getFormat();
			DataLine.Info info = new DataLine.Info(
                    Clip.class, 
                    ais.getFormat(), 
                    ((int) ais.getFrameLength() *
                        format.getFrameSize()));
            clip = (Clip) AudioSystem.getLine(info);
            clip.open(ais);
		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Plays a sound.
	 * Should probably be one thread per play to avoid 
	 * a short period of waiting for the sound to complete,
	 * but in real life you need to look at the dice before
	 * throwing again, so it's probably not important.
	 */
	public void play() {
		clip.setFramePosition(0);
		clip.start();
		// play only relevant part of the audio clip
		sleep(1);
		while(clip.isActive()) {
			if (clip.getFramePosition() > STOP_FRAME) {
				clip.stop();
			}
		}
	}

	private void sleep(int i) {
		try { Thread.sleep(i); } 
		catch(InterruptedException ie) { }
	}
	
}
